package com.walleipt.ipt_tools.utils;

import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.ReadContext;
import com.jayway.jsonpath.TypeRef;
import com.jayway.jsonpath.spi.json.JacksonJsonProvider;
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class _JsonPath {

	private static final Logger LOG = LoggerFactory.getLogger(_JsonPath.class);

	public static ReadContext parse( String json )
	{
		ReadContext ctx = JsonPath.using(Configuration.builder()
											.mappingProvider(new JacksonMappingProvider())
		            						.jsonProvider(new JacksonJsonProvider())
		        							.build())
									.parse(json) ;
		return ctx ;
	}
	
	public static String read(ReadContext ctx, String path )
	{
		try
		{
			String result = ConvertUtils.toString(ctx.read(path)) ;
			return StringUtils.isBlank(result)?null:result ;
		}
		catch( Throwable err )
		{
			LOG.error(err.getMessage() ) ;
			return null ;
		}
	}
	
	public static <T> T read(ReadContext ctx, String path, TypeRef<T> typeRef )
	{
		try
		{
			return ctx.read( path, typeRef ) ;
		}
		catch( Throwable err )
		{
			LOG.error(err.getMessage() ) ;
			return null ;
		}
	}
}
